<?php
namespace app\api\model;
use think\Model;
use think\Db;
use map\Map;
class Venue extends Model{
    //这里使用原始的query进行查询面向过程
    //这里是这样的当用户显示列表先根据名称查询结果显示在上面  然后拉取的是整个上海市
    public function select($orgins,$page_num,$page_size,$name){
       $res=$this->selectLists($orgins,$page_num,$page_size,$name);
       $result=$this->selecAllLists($orgins,$page_num,$page_size,$name);
       if(!empty($res)&&!empty($result))
       {
           $allresult=array_merge($res,$result);
       }
      
       $count=count($allresult);
       $data_new=array();
       $data_new['jiben']=$allresult;
       $data_new['total']=$count;
       //$allresult['total']=$count;
       return $data_new;
       //dump($allresult);
       $allresult=null;
       $res=null;
       $result=null;
        
    }
    
    public function selectLists($orgins,$page_num='1',$page_size='10',$name){
       $page_int=($page_num-1)*$page_size;
       $limit=$page_size;
       $res=Db::query("SELECT
DISTINCT p.id,
p.designation,
p.img,
c.`name`,
p.address
FROM
	gx_place p,
	gx_city c
WHERE
	p.area=c.id
AND 
c.upid=9
AND 
c.`name`=?
limit ?,?           
           ",array($name,$page_int,$limit));
        //上面是根据sql语句进行拼接的结果
        if(!empty($res))
        {
            //对结果进行重新组合
          foreach ($res as $key=>$va)
          {
              //$res[$key]['pic']=$this->getPic($va['id']);
              $res[$key]['address']=$va['name'].$va['address'];
              $res[$key]['location']=$this->getDistance($va['name'].$va['address']);
              $res[$key]['orgins']=$orgins;
              $res[$key]['distance']=$this->getJuli($orgins,$res[$key]['location']);
              unset($res[$key]['name']);//重新组合删除name值组合为address
              //重新组合的数组 id 名称 地址(area+address area c.name)
             
          }
           // dump($res);
            return $res;
            $res=null;
        }else{
            return 0;
        }
    }
    public function selecAllLists($orgins,$page_num='1',$page_size='10',$name){
        $page_int=($page_num-1)*$page_size;
        $limit=$page_size;
        $res=Db::query("SELECT
DISTINCT p.id,
p.designation,
p.img,
c.`name`,
p.address
FROM
	gx_place p,
	gx_city c
WHERE
	p.area=c.id
AND
c.upid=9
And
  c.`name` <>?
limit ?,?
           ",array($name,$page_int,$limit));
        //上面是根据sql语句进行拼接的结果
        if(!empty($res))
        {
            //对结果进行重新组合
            foreach ($res as $key=>$va)
            {
                //$res[$key]['pic']=$this->getPic($va['id']);
                $res[$key]['address']=$va['name'].$va['address'];
                $res[$key]['location']=$this->getDistance($va['name'].$va['address']);
                $res[$key]['orgins']=$orgins;
                $res[$key]['distance']=$this->getJuli($orgins,$res[$key]['location']);
                unset($res[$key]['name']);//重新组合删除name值组合为address
                //重新组合的数组 id 名称 地址(area+address area c.name)
               
            }
            // dump($res);
            return $res;
            $res=null;
        }else{
            return 0;
        }
    }
    
    
    /**
     * 
     * @param int $place_id 产地ID
     * @return string 产地封面返回图片列表第一个
     */
    public function getPic($place_id){
        try {
           $res=DB::name('place_pic')->where(array('place_id'=>$place_id))->find();
           if(!empty($res)){
               return $res['pic'];
           }else{
               return false;
           }
        }catch (\think\Exception $e){
            die($e->getMessage());
        }
    }
    /**
     *
     * @param int $place_id 产地ID
     * @return string 产地封面返回图片列表
     */
    public function getPics($place_id){
        try {
            $res=DB::name('place_pic')->field('pic')->where(array('place_id'=>$place_id))->select();
            if(!empty($res)){
                return $res;
            }else{
                return false;
            }
        }catch (\think\Exception $e){
            die($e->getMessage());
        }
    }
    
    /**
     * @param string $address 场馆地址
     * @return string $res 返回调用百度地图接口返回距离
     * 得到经纬度 就是根据用户首先微信点击附近场馆默认为微信授权获取得到用户的经纬度
     * 通过微信调用相应的接口获取用户的地理位置
     */
    public function getDistance($address){
        $Map=new Map();
        $res=$Map->getLocation($address);
        if($res['status']=='0'){
            return $res['result']['location'];
        }else{
            return 0;
        }
    }
    /**
     * @param string $lat 纬度值
     * @param string $lng 经度值
     * @return string $res 地区名称
     */
    public function getDistrict($lat,$lng){
        $Map=new Map();
        $res=$Map->getAddress($lat, $lng);
        //dump($res);
        if(!empty($res)&&$res['status']=='0'){
            return $res['result']['addressComponent']['district'];
        }else{
            return 0;
        }
    }
    /**
     * @param string $lat 纬度值
     * @param string $lng 经度值
     * @return string $res 修正过后的坐标
     */
    public function RetoLoaction($lat,$lng){
        $map=new Map();
        $res=$map->RetoLoadtion($lng, $lat);
        if($res['status']=='0'){
            return $res['result']['0'];
        }else{
            return 0;
        }
        
    }
    /**
     * 得到离商家的距离
     */
    public function getJuli($orgins,$destinations){
        $map=new Map();
        $res=$map->getWalking($orgins, $destinations);
        if($res['status']=='0'){
            $r=$res['result']['0']['distance']['value'];
            if($r>1000){
                $r=($r/1000)."km";
            }else{
                $r=$r.'m';
            }
            return $r;
        }else{
            return 0;
        }
    }
    /**
     * 场馆详情
     * @param int $id 场馆ID
     * @return array $res 返回详情信息
     */
    public function VenueDetails($id){
       $res=Db::query("SELECT
p.id,
p.designation,
p.address,
p.wifi,
p.img,
p.business_hours,
p.evaluate,
c.telphone,
city.`name`,
p.introduce
FROM
	gx_place p,
	gx_cuser c,
    gx_city city 
WHERE 
p.uid=c.id
AND
p.area=city.id
AND
p.id=?
",array($id));
       if(!empty($res)){
           foreach ($res as $key=>$va){
               $res[$key]['address']=$va['name'].$va['address'];
               $res[$key]['pic']=$this->getPics($va['id']);
               $res[$key]['introduce']=ch_arr(json_decode($va['introduce'],true));
               $result=$this->getEvalationInfo($va['id']);
               //dump($result);
               //$res[$key]['pinjia']=$result;
               $res[$key]['eva']=$result['count'];
               $res[$key]['xinshu']=$result['xinshu'];
           }
           return $res[0];
           $res=null;
       }
        
    }
    /**
     * 场馆详情
     * @param int $id 场馆ID
     * @return array $res 返回详情信息
     */
    public function VenueDetails_info($id){
        $res=Db::query("SELECT
p.id,
p.designation,
p.address,
p.img,
c.telphone,
city.`name`
FROM
	gx_place p,
	gx_cuser c,
    gx_city city
WHERE
p.uid=c.id
AND
p.area=city.id
AND
p.id=?
",array($id));
        if(!empty($res)){
            foreach ($res as $key=>$va){
                $res[$key]['address']=$va['name'].$va['address'];
                //$res[$key]['pic']=$this->getPics($va['id']);
                //$res[$key]['introduce']=ch_arr(json_decode($va['introduce'],true));
                $result=$this->getEvalationInfo($va['id']);
                //dump($result);
                //$res[$key]['pinjia']=$result;
                $res[$key]['eva']=$result['count'];
                //$res[$key]['xinshu']=$result['xinshu'];
            }
            //dump($res);
            return $res[0];
            $res=null;
        }
    
    }
    /**
     * 场馆详情
     * @param int $id 场馆ID
     * @return array $res 返回详情信息
     */
    public function VenueDetails2($datetime="",$id){
        set_time_limit(0);
        $res=Db::query("SELECT
p.id,
p.designation,
p.address,
p.img,
p.wifi,
p.business_hours,
c.telphone,
city.`name`,
p.introduce
FROM
	gx_place p,
	gx_cuser c,
    gx_city city
WHERE
p.uid=c.id
AND
p.area=city.id
AND
p.id=?
",array($id));
        if(!empty($res)){
            foreach ($res as $key=>$va){
                $res[$key]['address']=$va['name'].$va['address'];
                $res[$key]['pic']=$this->getPics($va['id']);
                $res[$key]['introduce']=ch_arr(json_decode($va['introduce'],true));
                $result=$this->getEvalationInfo($va['id']);
                $res[$key]['evaliate']=$result['evaluate'];
                $res[$key]['pinjia']=$result;
                $res[$key]['xinshu']=$result['xinshu'];
                //这里根据营业时间进行转换为数字即可 
                $res[$key]['cangdi']=$this->Venuestatus($datetime,$va['id'],$va['business_hours']);
            }
            return $res[0];
            $res=null;
        }
    
    }
    
    /**
     * @param int $id 场馆ID
     * @return array 返回评价信息 /并且返回每一个评论星数自行提取
     */
    public function getEvalationInfo($id){
       $res= Db::query("SELECT
cinfo.nickname,
eva.evaluation_time,
eva.content,
eva.grade,
eva.img
FROM
	gx_evaluate eva,
  gx_cuser_info cinfo
WHERE
cinfo.uid=eva.user_id
AND
eva.place_id=?",array($id));
        if(!empty($res)){
            $xinshu=0;//返回总的评价的心数
            $total=0;//统计所有的统计数
            $count=count($res);//返回评价数
            //$res['evaluate']=$count;
            foreach ($res as $va){
               $total+=$va['grade'];
            }
            $xinshu=$total/$count;
            //$res['xinshu']=round($xinshu,1);
           // $res['extra']=$res;
           $data_new=array();
           $data_new['jiben']=$res;
           $data_new['count']=$count;
           $data_new['xinshu']=round($xinshu,1);
            return $data_new;
        }else{
            return 0;
        }
    }
    /***
     * 场馆场地位
     * @param int $id 场地ID
     * @param int $datetime 日期
     * @param int $length 营业时间 如果是24小时 就是16个 (24-8)16 如果是23 就是23-8
     * @return array $result;
     */
    public function Venuestatus($datetime,$id,$length="16"){
        //这里是场馆+场地的信息 就是点击异步提取的方式点击 11-8 时候就进行取出数据
        //这里我给出15个数组 也就是默认的二维数组的 0就代表 8-9的这一个数据
        // 0里面就是存放是在8-9的场地 并且有一个统计 器械数是 会返回一个
        
        //array(array('qixie'=>array('use'=>1,'total'=>5),'course'=>array('use'=>1,'total'=>8)));
        $data=array();
        $start=8;
        $end=9;
        for($i=0;$i<16;$i++){
          // DB::name('venue_status')->where()->find();
         $res=Db::name('venue_status')->field('qtotal,ctotal,fee,xishu')->where(array('riqi'=>$datetime,'startime'=>$start,'endtime'=>$end,'place_id'=>$id))->find();
         //$time=$datetime." ".$start.":00-".$end.":00";
       
         $re=empty($this->getVeneueStatus3($datetime,$id)[0][$start.'-'.$end])?0:$this->getVeneueStatus3($datetime,$id)[0][$start.'-'.$end];
         //dump($re);
         $re2=empty($this->getVeneueStatus3($datetime, $id)[1][$start.'-'.$end])?0:$this->getVeneueStatus3($datetime,$id)[1][$start.'-'.$end];
         $res['quse']=$re;
         $res['cuse']=$re2;
         $data[]=$res;
         $start++;
         $end++;
        
           //echo $start.":00"."-".$end.":00".'<br/>';
        }
       if(!empty($data)){
           //dump($data);
           return $data;
       }else{
           return 0;
       }
    }
    //有俩个思路
    //页面当显示 2017.11.9 之后点击是一个插件显示 
    //然后初始化的时候 js动态生成这个 就是 2017.11.9+start=8:00 end=9:00 
    //进行发送 这里接口 就是 接受一个 place_id riqi 参数进行动态返回数据 即可
    /**
     * @param int $place_id 场馆ID
     * @return string $res
     */
    public function getVenueUseToal($datatime,$startime,$endtime,$place_id){
       
        $sql=Db::name('appointment_gym')->field('id')->where('riqi',$datatime)
        ->where('startime',$startime)
        ->where('endtime',$endtime)
        ->where('place_id',$place_id)
        ->where('type','2')
        ->select();
        dump($sql);
        //因为课程数和场地数不一致的所以还是要分开只不过在计算type=2时可以一样type=1 type=2 俩份即可
    }
    public function getVenueUseStatus($datetime,$startime,$endtime,$place_id){
        //一样的如果
        //这里数据库变了变成了一样的 日期 开始时间 结束时间
      $where=array('place_id'=>$place_id,'riqi'=>$datetime,'startime'=>$startime,'endtime'=>$endtime,'status'=>1,'type'=>1);
      $res=Db::name('appointment_gym')->field('id')->where($where)->select();
      return count($res);
        
    }
    //这里重新整理了为了好在页面显示将 appoint_time 定义为正常的预约时间 strtime,endtime 定义为加的课程数 
    public function getVenueUseStatus2($datetime,$startime,$endtime,$place_id){
        //一样的如果
        $where=array('place_id'=>$place_id,'riqi'=>$datetime,'startime'=>$startime,'endtime'=>$endtime,'status'=>1,'type'=>2);
        $res=Db::name('appointment_gym')->field('id')->where($where)->select();
        return count($res);
    }
    public function getVeneueStatus3($datetime,$place_id){
        $res=Db::name('appointment_gym')->field('appoint_time,startime,endtime')->where(array('riqi'=>$datetime,'place_id'=>$place_id))->select();
        $res_jiqi=array();
        $res_c=array();
        if(empty($res)){
            return 0;
        }else{
            foreach ($res as $va){
                $res_jiqi[]=$this->fe($va['appoint_time']);
                 
                if($va['startime']){
                    $res_c[]=$this->fe($va['startime']."-".$va['endtime']);
                }
            }
        }
        $re=[];
        foreach ($res_jiqi as $key=>$va){
            foreach ($va as $key=>$s){
                array_push($re, $s);
            }
        }
        
        $re2=[];
        if(!empty($res_c)){
            foreach ($res_c as $va){
                foreach ($va as $s){
                    array_push($re2, $s);
                }
            }  
        }
        $jicuse=array_count_values($re);
        $cuse=array_count_values($re2);
        $conxin=array();
        $conxin[0]=$jicuse;
        $conxin[1]=$cuse;
        return $conxin;
        
       
    }
    
    public function fe($str){
        set_time_limit(0);
        $str=str_ireplace(":00","", $str);
        $data=explode('-', $str);
        $start=$data[0];
        $end=$data[1];
        $res=array();
         
        for ($i=$start;$i<=$end;$i++){
            $s="";
            if($i==$end)break;
            $s.=$i."-".($i+1);
            $res[]=$s;
        }
         
        return $res;
    }
    //页面如何显示这个8:00-9:00已经有了人预约的呢
    //首先根据 8:00-9:00查询这个数据库有没有记录 如果有你怎么知道是场馆还是课程 
    //就是知道了 你怎么知道这个人是否预约成功了如果预约成功了这几个条件才加一
    public function VenueDetailDuo($user_id){
        $res=Db::query("SELECT
	p.id,
	p.designation,
	p.address,
	p.wifi,
	p.business_hours,
	p.evaluate,
	c.telphone,
	city.`name`,
	p.introduce
FROM
	gx_place p,
	gx_cuser c,
	gx_city city
WHERE
	p.uid = c.id
AND p.area = city.id
AND p.id IN (
	SELECT
		f.place_id
	FROM
		gx_favorite f
	WHERE
		f.user_id = ?
)
",array($user_id));
        if(!empty($res)){
            foreach ($res as $key=>$va){
                $res[$key]['address']=$va['name'].$va['address'];
                $res[$key]['pic']=$this->getPics($va['id']);
                $res[$key]['introduce']=ch_arr(json_decode($va['introduce'],true));
                $result=$this->getEvalationInfo($va['id']);
                $res[$key]['pinjia']=$result;
                $res[$key]['xinshu']=$result['xinshu'];
            }
            return $res;
            $res=null;
        }
    
    }
    
    /**
     * 
     * @param unknown $data
     * @return unknown
     */
    public function getFee($data){
        //默认一个场馆的系数 和价格一样
       $res= Db::name('venue_status')
        ->field('fee,xishu')
        ->where(array('place_id'=>$data['place_id']))
        ->find();
       //可以的fee,xishu 然后进行开始结束 技术啊
       return $res;
    }
    public function getFeeTodal($data){
       $res=Db::name('venue_status')->
        field('fee,xishu')
        ->where(array('riqi'=>$data['riqi'],
            'startime'=>$data['startime'],
            'endtime'=>$data['endtime'],
            'place_id'=>$data['place_id'],
            )
            )->find();
        return $res;
    }
    /**
     * 
     * @param int  $place_id 场馆ID
     * @return array $res
     */
    public function getItem($place_id){
     $res=Db::query("SELECT
    p.id,
    p.img,
	p.designation,
	c.`name`
FROM
	gx_place p,
	gx_city c
WHERE
	c.id = p.area
AND p.id = ?
           ",array($place_id));
     return $res[0];
    }
    /**
     * 场馆详情
     * @param int $id 场馆ID
     * @return array $res 返回详情信息
     */
    public function VenueDetail_Item($id){
        $res=Db::query("SELECT
p.id,
p.designation,
p.wifi,
p.img,
p.business_hours
FROM
	gx_place p
WHERE
p.id=?
",array($id));
        if(!empty($res)){
            foreach ($res as $key=>$va){
                //$res[$key]['address']=$va['name'].$va['address'];
                //$res[$key]['pic']=$this->getPics($va['id']);
                //$res[$key]['introduce']=ch_arr(json_decode($va['introduce'],true));
                $result=$this->getEvalationInfo($va['id']);
                //dump($result);
                //$res[$key]['pinjia']=$result;
                //$res[$key]['eva']=$result['count'];
                $res[$key]['xinshu']=$result['xinshu'];
            }
            return $res[0];
            $res=null;
        }
    
    }
}